package com.qingluan.pyi;

import java.util.Date;

import org.codehaus.jackson.annotate.JsonAnyGetter;
import org.codehaus.jackson.node.IntNode;
import org.json.JSONException;
import org.json.JSONObject;

import com.qingluan.arguments.ARGUMENTS;
import com.qingluan.data.Personal_Info_database;
import com.qingluan.server.LongSocketServer;
import com.qingluan.server.WebSocketBroadcast;
import com.qingluan.server.WebSocketBroadcast.ReceiverListener;
import com.qingluan.web.AsyncRecive.ListenJsonResult;
import com.qingluan.web.HttpTemplate;

import android.nfc.Tag;
import android.os.Bundle;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.TextureView;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
	
	//view widget area
	private TextView info_view;
	private LinearLayout btn_area;
	private LinearLayout info_area;
	private LinearLayout teacherLayout ;
	private Button  teacher_control;
	
//	context area
	private Context context_this_activity;
	private String UID;
	private WebSocketBroadcast boadcastReceiver;
	private String tag = this.getClass().getName();
	
//	soem info 
	private long S_time;
	private boolean ifBuild =  false;
	private boolean ifLogin = false;
	private String uid;
//	control tag area
	private boolean ifStart = false;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		
		uid = getIntent().getExtras().getString("uid");
		info_view = (TextView)findViewById(R.id.info_text);
		btn_area = (LinearLayout) findViewById(R.id.bt_area);
		info_area = (LinearLayout)findViewById(R.id.info_area);
		teacherLayout = (LinearLayout) findViewById(R.id.teacher_control_area);
		teacher_control = (Button)findViewById(R.id.start_answer);
		
		if (!uid.equals("000000")){
			
			teacherLayout.setVisibility(View.GONE);
		}
//		initialization 
		Init();
		
//		registr a action 
		boadcastReceiver = new WebSocketBroadcast();
		boadcastReceiver.setReceiveListern(new ReceiverListener(){

			@Override
			public void onReceive(String info) {
				// TODO Auto-generated method stub
				if (info.equals("ON")){
					Toast.makeText(context_this_activity, info, Toast.LENGTH_SHORT).show();
					ifBuild = true;
				}else{
					try {
						JSONObject JsonInfo = new JSONObject(info);

						String status = JsonInfo.getString("status");
						if (status .equals("login")){
							Toast.makeText(context_this_activity, "add to this room", Toast.LENGTH_SHORT).show();
							
						}else if (status.equals("talk")){
							String contentString = JsonInfo.getString("content");
							info_view.setText(contentString);
							startAnswer(contentString);
						}
						
						
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						Log.d(tag,"Not json");
					}
				}
				
				
				
				
			}
			
		});
		IntentFilter filter = new IntentFilter();
		filter.addAction (ARGUMENTS.RECEIVE_SERVER);
		registerReceiver(boadcastReceiver, filter );
		
		
		
		
		
		startService();
		
		
	}

	
	private void Init(){
		UID = getIntent().getStringExtra("uid");
		context_this_activity = getApplicationContext();
		HiddenButtons();

		
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		LoginModule loginModule =new LoginModule();
		loginModule.start();
		
	}
	
	private void startService(){
		Intent intent = new Intent(MainActivity.this,LongSocketServer.class);
		context_this_activity.startService(intent);
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		
		
	}
	
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		unregisterReceiver(boadcastReceiver);
		
		super.onStop();
	}
	
	/*
	 * handle buttons
	 */
	public void HiddenButtons(){
		btn_area.setVisibility(View.GONE);
		btn_area.invalidate();
	}
	
	public void BackButtons(){
		btn_area.setVisibility(View.VISIBLE);
		btn_area.invalidate();
	}
	
	
	public void startAnswer(String info){
//		TextView extend_view = new TextView(MainActivity.this);
//		extend_view.setText(info);
//		extend_view.setGravity(Gravity.CENTER);
//		
//		info_area.addView(extend_view);
//		info_area.invalidate();
		info_view.setText(info);
		S_time = System.currentTimeMillis();
		btn_area.setVisibility(View.VISIBLE);
		
	}
	
	public void startAnswerForTeacher(View view){
		if (! ifStart){
			Intent intent = new Intent();
			intent.setAction(ARGUMENTS.PUSH_SERVICE);
			JSONObject jsonInfoJsonObject = new JSONObject();
			try {
				jsonInfoJsonObject.put("status", "talk");
				jsonInfoJsonObject.put("content", "Start Answer !!");
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			BackButtons();
			intent.putExtra(ARGUMENTS.KEY,jsonInfoJsonObject.toString());
			sendBroadcast(intent);
			teacher_control.setText("Start Statistic !");
			ifStart = true;
		}else if(ifStart){
			
			JSONObject json = new JSONObject();
			try {
				json.put("command", "this");
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			HttpTemplate.Post(ARGUMENTS.STATISTIC_IP, ARGUMENTS.JSON_STATISTIC, json, new ListenJsonResult(){

				@Override
				public void success(String info) {
					// TODO Auto-generated method stub
					info_view.setText("statistic succefful !");
					ifStart = false;
					teacher_control.setText("Start !!");
				}

				@Override
				public void fail(String error) {
					// TODO Auto-generated method stub
					Toast.makeText(context_this_activity, error, Toast.LENGTH_SHORT).show();
				}
				
			});
		}
	}
	
	/*
	 * post answer
	 */
	public void choise(View view) throws JSONException{
		HiddenButtons();
		Button bt = (Button) view;
		String select = bt.getText().toString();
		String user = UID;
		final long N_time = System.currentTimeMillis();
		
		
		JSONObject json = new JSONObject();
		json.put("name", user);
		json.put("select",select);
		
		HttpTemplate.Post(ARGUMENTS.ANSWER_IP,ARGUMENTS.JSON_ANSWER_POST,json,new ListenJsonResult() {
			
			@SuppressWarnings("deprecation")
			@Override
			public void success(String info) {
				// TODO Auto-generated method stub
				try {
					JSONObject json = new JSONObject(info);
					String result = json.getString("if_T");
					String time = new Date( N_time - S_time).toGMTString();
					String new_info = result+"\n用时 ：" + time;
					
					info_view.setText(new_info);
					
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			
			@Override
			public void fail(String error) {
				// TODO Auto-generated method stub
				Toast.makeText(getApplicationContext(), error, Toast.LENGTH_SHORT).show();

				//let button display again
				BackButtons();
				
			}
		});
	}
	
	
	
//	
//	
//	#############################################################################################################################
//	#############################################################################################################################
//	#############################################################################################################################
//	
	
	
	class LoginModule extends Thread {
		@Override
		public void run() {
			// TODO Auto-generated method stub
			int count = 0;
			while (true){
				count += 1;
				if (count == 30){
					break;
				}
				if (ifBuild){
					JSONObject loginJson = new JSONObject();
					try {
						if(! ifLogin){
							loginJson.put("status", "login");
							loginJson.put("name", uid);
							Intent intent = new Intent();
							intent.putExtra(ARGUMENTS.KEY, loginJson.toString());
							intent.setAction(ARGUMENTS.PUSH_SERVICE);
							sendBroadcast(intent);
							ifLogin = true;
						}else{
							break;
						}
						
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}else {
					try {
						Thread.sleep(1000);
						Log.d(tag, "logain fail ...try again");
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			
			try {
				sleep(50);
				this.interrupt();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
			
			
			
		}
	}
	
}
